import Axios from "axios";
import useAuth from "../stores/auth.store";
import { message } from "ant-design-vue";

const request = Axios.create({
  baseURL: "/",
  timeout: 5000,
});

request.interceptors.request.use(
  (config) => {
    const auth = useAuth();
    if (auth.token != "") {
      config.headers!!.Authorization = `Bearer ${auth.token}`;
    }

    return config;
  },
  (error) => {
    console.log("request.error: ");
    message.error(error.message);
  }
);

request.interceptors.response.use(
  async (response): Promise<any> => {
    // console.log('response: ', response);
    const auth = useAuth();
    if (response.data.code === 10000 && auth.refreshToken != "") {
      // console.log('刷新token');
      await auth.refreshTokenAsync();

      const result = await request(response.config);
      return result;
    }
    if (response.data.code === 10010) {
      // console.log('10010 错误');
      auth.logout();
      message.error("刷新token失败, 请重新登录");
      return Promise.reject();
    }

    return response.data;
  },
  (error) => {
    // console.log('error: ', error.response);
    switch (error.response.status) {
      case 400:
        // 数据提交验证错误
        //   if (error.response.data.code === 10400) {
        //     validateErrors.setErrors(error.response.data.data);
        //   }
        break;
      case 401:
      case 403:
      default:
        message.error(error.response.data.msg);
    }
  }
);

export default request;
